package com.aischool.eduorg.api;

import com.aischool.common.kit.Md5Kit;
import com.aischool.common.model.AiParent;
import com.aischool.common.model.SysUser;
import com.aischool.params.AiParentParams;
import com.aischool.routes.RouteMapping;
import com.aischool.service.AiClassService;
import com.aischool.service.AiKindredService;
import com.aischool.service.AiParentService;
import com.aischool.service.AiStudentService;
import com.aischool.service.SysUserAppService;
import com.aischool.service.SysUserRoleService;
import com.aischool.service.SysUserService;
import com.aischool.utils.AppUtil;
import com.aischool.utils.DateUtil;
import com.aischool.utils.JsonCodeEnum;
import com.aischool.utils.JsonResult;
import com.aischool.utils.RegexUtil;
import com.aischool.utils.StateEnum;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

@RouteMapping(url = "/api/eduorg/parent")
public class ParentController extends Controller {

	@Inject 
	AiParentService aiParentService;
	@Inject
	AiClassService aiClassService;
	@Inject
	AiKindredService aiKindredService;
	@Inject
	SysUserService sysUserService;
	@Inject
	SysUserAppService sysUserAppService;
	@Inject
	SysUserRoleService sysUserRoleService;
	@Inject
	AiStudentService aiStudentService;
	
	public void getPage() {
		// 结果类
		JsonResult jr = new JsonResult();
		// 参数类
		AiParentParams params = new AiParentParams();
		
		int org_id = this.getAttrForInt("login_org_id");
		params.setOrgId(org_id);
				
		params.setPageNo(getParaToInt("pageNo", 1));
		params.setPageSize(getParaToInt("pageSize", AppUtil.Default_PageSize));

		params.setState(getInt("state", StateEnum.ALL.getState()));
		
		params.setKeywords(get("keywords",""));
		
		// 获取分页
		Object pageData = aiParentService.getPage(params);
		
		jr.setDicKV("pageData", pageData);
		
		jr.setEnum(JsonCodeEnum.Success);
		renderJson(jr.Dic);
	}
	
	/**
	 * 获取单个信息
	 */
	public void getOne() {
		// 结果类
		JsonResult jr = new JsonResult();
		
		int org_id = this.getAttrForInt("login_org_id");
		int parent_id = getParaToInt("id",0);
		
		Object obj = aiClassService.getAll(org_id, 1);
		if (obj != null) { jr.setDicKV("listclass", obj); }
		
		obj = aiKindredService.getAll();
		if (obj != null) { jr.setDicKV("listkindred", obj); }
		
		if (parent_id > 0) {
			Record rdp = aiParentService.getOne(parent_id);
			if (rdp != null) { 
				jr.setDicKV("oneinfo", rdp); 
				
				obj = aiStudentService.getStudents(rdp.getInt("class_id"));
				if (obj != null) { jr.setDicKV("liststudent", obj); }
			}
		}

		jr.setEnum(JsonCodeEnum.Success);
		renderJson(jr.Dic);
	}
	
	public void save() {
		// 结果类
		JsonResult jr = new JsonResult();
		
		int login_user_id = this.getAttrForInt("login_org_id");
		int org_id = this.getAttrForInt("login_org_id");
		// 表单转换类
		int parent_id = getParaToInt("parent_id", 0);
		AiParent info = getModel(AiParent.class, "", true);
		
		SysUser infou = new SysUser();
		
		// 密码
		String pwd1 = getPara("user_pwd","");
		if (pwd1.length()>0) {
			infou.setLoginPwd(Md5Kit.MD5For8(pwd1));
		}

		if (StrKit.isBlank(info.getParentName())) {
			jr.appendMsg("请输入学生姓名！");
		}else if (StrKit.isBlank(info.getParentMobile()) || !RegexUtil.isMobile(info.getParentMobile())) {
			jr.appendMsg("请输入正确的手机号码！");
		}else if (parent_id <= 0 && StrKit.isBlank(getPara("user_pwd",""))) {
			jr.appendMsg("请输入登录密码！");
		}else {
			
			info.setUpdateTime(DateUtil.getTimestamp());
			info.removeNullValueAttrs();
			
			boolean bf = false;
			if (parent_id >0) {
				Record rd = aiParentService.getOne(parent_id);
				if (rd != null && rd.getInt("org_id") == org_id) {

					bf = Db.tx(() -> {
						boolean bft = info.update();; // update result
						if (bft) {
							if (pwd1.length()>0) {
								infou.setUserId(info.getUserId());
								infou.setUserState(info.getParentState()); // state sync 
								if (StrKit.notBlank(info.getParentName())) {
									infou.setUserName(info.getParentName());
								}
								infou.removeNullValueAttrs();
								bft = infou.update();
							}
						}
						return bft;
					});
				}
			}else {
				// 新增用户，查询手机号
				Record rdu1 = sysUserService.getUserByMobile(info.getParentMobile());
				if (rdu1 != null) {
					jr.appendMsg("该手机号码已注册，请更换手机号码！");
				}else {
					// 插入user
					infou.setLoginName(info.getParentMobile());
					infou.setUserMobile(info.getParentMobile());
					infou.setUserName(info.getParentName());
					infou.setRegTime(DateUtil.getTimestamp());
					infou.setUpdateTime(DateUtil.getTimestamp());
					infou.setUserState(1); // state sync
					infou.setIsLock(false);
					infou.removeNullValueAttrs();
					
					// 插入家长
					info.setOrgId(org_id);
					info.setAddUserid(login_user_id);
					info.setAddTime(DateUtil.getTimestamp());
					info.setParentState(1); // state sync
					info.removeNullValueAttrs();
					
					bf = Db.tx(() -> {
						boolean bft = true; // 添加结果
						int user_id = 0;
						bft = infou.save();
						if (bft) {
							user_id = infou.getUserId();
							// 设置用户应用权限
							sysUserAppService.setUserApp(user_id, 7);
							// 设置用户应用角色
							sysUserRoleService.setUserAppRole(user_id, 7, 3);
							
							info.setUserId(user_id);
							bft = info.save();
						}
						return bft;
					});
				}
			}
			
			if (bf) {
				jr.setEnum(JsonCodeEnum.Success);
			}
		}
		renderJson(jr.Dic);
	}
	
	public void del() {
		// 结果类
		JsonResult jr = new JsonResult();
		boolean bf = false;

		int org_id = this.getAttrForInt("login_org_id");
		// 表单转换类
		int parent_id = getParaToInt("id", 0);
		if (parent_id > 0) {
			bf = aiParentService.delForOrg(org_id, parent_id);
		}else {
			String ids = get("ids","");
			bf = aiParentService.delMoreForOrg(org_id, ids);
		}
		
		if (bf) {
			jr.setEnum(JsonCodeEnum.Success);
		}else {
			jr.setEnum(JsonCodeEnum.Faild);
		}
		
		renderJson(jr.Dic);
	}
}
